package com.bdqn.t350.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.bdqn.t350.entity.Powerbattery;
import com.bdqn.t350.service.PowerbatteryService;
import com.bdqn.t350.service.PowerbatteryServiceImp;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.http.Part;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class UploadAliYunUtil {
    //阿里云域名
    public static final String ALI_DOMAIN = "https://dengren.oss-cn-guangzhou.aliyuncs.com/";
    //地域节点
    //static final String endpoint = "http://oss-cn-guangzhou.aliyuncs.com";
    static final String endpoint = "http://oss-cn-guangzhou.aliyuncs.com";
    //Bucket名称
    //static final String bucket = "yuanxiaoxiang";
    static final String bucket = "dengren";


    //阿里云AccessKey管理生成的信息,在阿里云账号里面查找该信息
    static final String accessKeyId = "LTAIu4Fh1RFX93300GKyWE";
    static final String accesskeySecret = "UD4uJ777I93RonobJrxXi91kXR";


    /**
     * 返回oss 上传文件的 url地址
     *
     * @param part
     * @return
     */
    public static Map<String,String> uploadImage(Part part) {
        //获取上传文件的真实文件名
        String originalFilename = extractFileName(part);
        //截取文件的.和后缀
        String ext = "." + FilenameUtils.getExtension(originalFilename);
        //生成uuid唯一码
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //生成上传文件的名称 fileName = uuid
        String fileName = uuid + ext;
        //oss客户端对象-类似你要连接mysql是不是需要去通过账号密码地址等信息去连接数据库
        //通过账号,key等信息去连接阿里云存储
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accesskeySecret);
        try {
            //具体将文件写入到那个地方
            ossClient.putObject(bucket, fileName, part.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
         //   return "";
        }
        //关闭连接
        ossClient.shutdown();
        //将文件名等信息返回给servlet
        HashMap<String,String> map = new HashMap<>();
        map.put("realFileName",originalFilename);
        map.put("saveFileName",fileName);
        map.put("ext",ext);
        return map;
    }




    /**
     * 从http header中提取上传文件的名称
     *
     * @param part
     * @return
     */
    private static String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }
}
